import 'package:aichat_flutter_wallet/kai_print.dart';
import 'package:aichat_flutter_wallet/module/module_browser/pages/browser.dart';
import 'package:aichat_flutter_wallet/module/module_browser/provider/browser_proviser.dart';
import 'package:aichat_flutter_wallet/module_common/bridge/native_channel_bridge.dart';
import 'package:aichat_flutter_wallet/module_common/provider/wallet_info_provider.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/dialog/dialog_utils.dart';
import 'package:flutter/material.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_database/sp.dart';
import 'package:lib_util/lib_util.dart';
import '../../../module_common/provider/nav_key.dart';

class WebSiteInfoItem {
  final String websiteImg;
  final String websiteName;
  final String websiteTag;
  final String websiteUrl;

  WebSiteInfoItem(
      {required this.websiteImg,
        required this.websiteName,
        required this.websiteUrl,
        this.websiteTag = ''});
}

/**
 * 来用控制进入webview前的逻辑
 */
class BeforeBrowserController {
  static final BeforeBrowserController _instance =

  BeforeBrowserController._init();

  // 是否通过搜索进入
  bool isSearchIn = false;
  String websiteImg = '';
  String websiteName = '';
  String websiteTag = '';
  String websiteUrl = '';

  setSearchIn(bool value) {
    isSearchIn = value;
  }

  setWebsiteInfo(WebSiteInfoItem webSiteInfoItem) {
    websiteName = webSiteInfoItem.websiteName;
    websiteImg = webSiteInfoItem.websiteImg;
    websiteTag = webSiteInfoItem.websiteTag;
    websiteUrl = webSiteInfoItem.websiteUrl;
    setSearchIn(false);
  }

  factory BeforeBrowserController() {
    return _instance;
  }

  BeforeBrowserController._init();

  get instance => _instance;
}

// 判断浏览器跳转
doGotoBrowser(
    {required String webUrl,
      BuildContext? context,
      Function? callback,
      bool isSearchIn = true,
      WebSiteInfoItem? webSiteInfoItem}) {
  if (webUrl.isEmpty) return;
  String url = '';
  NavKey.getContext()
      .read<BrowserProvider>()
      .setCurWebsiteInfo(website: webSiteInfoItem);
  if (!webUrl.startsWith('http') && !webUrl.startsWith('https')) {
    url = 'https://' + webUrl;
  } else {
    url = webUrl;
  }
  // 设置标签信息
  if (isSearchIn) {
    BeforeBrowserController().setSearchIn(true);
  } else {
    BeforeBrowserController().setWebsiteInfo(webSiteInfoItem!);
  }
  var list = SP().getBrowserInsideValid();
  if (!list.contains(url)) {
    DialogUtils.showBrowserInside(context: context!, url: url);
  } else {
    if (callback != null) {
      callback();
    }
    goBrowser(url: url);
  }
}

// 向浏览器注入js
void goBrowser({String url = 'https://baidu.com'}) {
  String token1 = '${NativeChannelBridge.instance.appCommMsg?.token}';
  String email = '${NativeChannelBridge.instance.appCommMsg?.email}';
  Future<String> tokenJs = Future.value(
      "window._kaipayToken='${token1}';window._kaipayEmail='${email}';");
  // Log.logger.e('${NativeChannelBridge.instance.appCommMsg?.token}---token');
  BuildContext context = NavKey.navKey.currentContext!;
  List<Future<String>>? jsScriptFuture = [];
  Wallet? wallet = NavKey.getContext().read<WalletInfoNotifier>().wallet;
  Future<String> postJs = Future.value(
      'window.Kai={postMessage:function(json){window.flutter_inappwebview.callHandler("postMessage",json)},ethTransactionResult:function(json){window.flutter_inappwebview.callHandler("ethTransactionResult",json)}}');
  // 注入evm
  if (wallet != null) {
    // Future<String> vConsoleJs =
    // DefaultAssetBundle.of(context).loadString('assets/js/vconsole.js');
    Future<String> trustJs = DefaultAssetBundle.of(context)
        .loadString('assets/chaincore/trust_min.js');
    Map<String, dynamic> map =
    NavKey.getContext().read<BrowserProvider>().getNetworkAndNode();
    Chain chain = map['chain'];
    NodeInfo node = map['node'];
    Future<String> initJs = Future.value(
        'var config={ethereum:{chainId: ${chain.evmInfo!.chainId},rpcUrl:"${node.url}"},solana:{cluster:"mainnet-beta"},isDebug:false};trustwallet.ethereum=new trustwallet.Provider(config);trustwallet.solana=new trustwallet.SolanaProvider(config);trustwallet.postMessage=(json)=>{window.flutter_inappwebview.callHandler("postMessage",JSON.stringify(json))};window.ethereum=trustwallet.ethereum;window.ethereum.isMetaMask=true;window.ethereum.isKai=true;');
    // vConsoleJs,
    jsScriptFuture = [ tokenJs ,trustJs, initJs, postJs];
  } else {
    jsScriptFuture = [ tokenJs, postJs];
  }

  // config
  //  'window.ethereum.selectedAddress="0xe2be444ef66780a7d5b5a81604229935b99823fa";'

// 注入tron
  // Future<String> tronWebJs =
  //     DefaultAssetBundle.of(context).loadString('assets/chaincore/tronweb.js');
  // Future<String> kaiWalletTronJs = Future.value(
  //     'window._kaiwallet={postMessage:function(j){window.flutter_inappwebview.callHandler("postMessage",j)}};');
// tron 回调处理
  // Future<String> tronPostMessageJs = DefaultAssetBundle.of(context)
  //     .loadString('assets/chaincore/inject_tron.js');
  Future.wait(jsScriptFuture).then((value) {
    MaterialPageRoute route = MaterialPageRoute(builder: (_) {
      return BrowserPage(
        url: url,
        userScripts: value,
      );
    });
    Navigator.of(context).push(route);
  }).onError((error, stackTrace) {
    kaiPrint(error);
  });
}
